import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import {
  getArtistsApi,
  getBannerApi,
  getDJToplistApi,
  getPersonalizedApi,
  getRankListApi,
  getTopAlbumApi
} from '@/server/modules/discover'

// 获取发现页顶部轮播图
export const fetchDiscoverTopBanner = createAsyncThunk(
  'fetchDiscover',
  async (_, { dispatch }) => {
    const banners = await getBannerApi()
    dispatch(setTopBanner(banners))
  }
)

// 获得推荐歌单
export const fetchDiscoverPersonalized = createAsyncThunk(
  'fetchDiscoverPersonalized',
  async (_, { dispatch }) => {
    const personalized = await getPersonalizedApi(8)
    dispatch(setPersonalized(personalized))
  }
)

// 获得新碟上架数据
export const fetchDiscoverNewAlbum = createAsyncThunk(
  'fetchDiscoverNewAlbum',
  async (_, { dispatch }) => {
    const newAlbum = await getTopAlbumApi()
    dispatch(setNewAlbum(newAlbum))
  }
)

// 获得排行榜数据
export const fetchDiscoverRankList = createAsyncThunk(
  'fetchDiscoverRankList',
  async (_, { dispatch }) => {
    const rankingIds = [19723756, 3779629, 2884035]
    const promises: Promise<any>[] = []
    rankingIds.forEach((id) => {
      promises.push(getRankListApi(id))
    })
    Promise.all(promises).then((res) => {
      const playlists = res
        .filter((item) => item.playlist)
        .map((item) => item.playlist)
      dispatch(setRankList(playlists))
    })
  }
)

// 获得歌手列表
export const fetchDiscoverSingerList = createAsyncThunk(
  'fetchDiscoverSingerList',
  async (_: any, { dispatch }) => {
    const res: any = await getArtistsApi(_.cat)
    dispatch(setSingerList(res.artists))
  }
)

// 获得最热主播榜
export const fetchDiscoverHotDJ = createAsyncThunk(
  'fetchDiscoverHotDJ',
  async (_, { dispatch }) => {
    const res: any = await getDJToplistApi()
    dispatch(setDjHot(res.toplist))
  }
)

interface IState {
  topBanner: any[]
  personalized: any[]
  newAlbum: any[]
  rankList: any[]
  singerList: any[],
  hotDJ: any[]
}

const initialState: IState = {
  topBanner: [], // 发现页顶部轮播图
  personalized: [], // 推荐歌单
  newAlbum: [], // 新碟上架
  rankList: [], // 排行榜
  singerList: [], // 歌手列表
  hotDJ: [] // 最热主播榜
}

const discoverSlice = createSlice({
  name: 'discover',
  initialState,
  reducers: {
    setTopBanner(state, { payload }) {
      state.topBanner = payload.banners
    },
    setPersonalized(state, { payload }) {
      state.personalized = payload.result
    },
    setNewAlbum(state, { payload }) {
      state.newAlbum = payload.albums
    },
    setRankList(state, { payload }) {
      state.rankList = payload
    },
    setSingerList(state, { payload }) {
      state.singerList = payload
    },
    setDjHot(state, { payload }) {
      state.hotDJ = payload
    }
  }
})

export const {
  setTopBanner,
  setPersonalized,
  setNewAlbum,
  setRankList,
  setSingerList,
  setDjHot
} = discoverSlice.actions

export default discoverSlice.reducer
